package net.magicalcloud.magicalcloud.transfer;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;

import net.magicalcloud.magicalcloud.transfer.bean.DownloadInfo;

import java.io.File;
import java.io.FileFilter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 下载 服务
 * Created by Pei on 2018/6/12.
 */

public class DownloadService extends Service {

    /**
     * binder对象
     */
    private DownloadBinder binder;

    /**
     * 线程池
     */
    private ExecutorService mThreadPool ;

    /**
     * cpu默认核数（android应用属于io密集型，线程池大小一般设置为 2N+1
     */
    private final int DEFAULT_CPU_CORES=4;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        if(binder==null){
            binder=new DownloadBinder();
        }
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public void download(DownloadInfo downloadInfo){
        mThreadPool= Executors.newFixedThreadPool(2*getNumberOfCPUCores()+1);
        //初始化新的下载任务
        InitThread thread = new InitThread(DownloadService.this,downloadInfo,mThreadPool);
        if(!mThreadPool.isShutdown()) {
            mThreadPool.execute(thread);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 获取cup核心数
     * @return 核心数
     */
    public int getNumberOfCPUCores() {
        int cores;
        try {
            cores = new File("/sys/devices/system/cpu/").listFiles(CPU_FILTER).length;
        } catch (SecurityException | NullPointerException e) {
            cores = DEFAULT_CPU_CORES;
        }
        return cores;
    }

    private static final FileFilter CPU_FILTER = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            String path = pathname.getName();
            //regex is slow, so checking char by char.
            if (path.startsWith("cpu")) {
                for (int i = 3; i < path.length(); i++) {
                    if (path.charAt(i) < '0' || path.charAt(i) > '9') {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }
    };


    /**
     * 绑定服务类
     */
    public class DownloadBinder extends Binder {
        public  DownloadService getService () {
            return DownloadService.this;
        }
    }
}
